package com.novunda.platform.web.config;

import com.google.common.collect.Maps;
import com.novunda.platform.common.resolver.GlobalExceptionResolverFilter;
import com.novunda.platform.config.AppConfig;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Map;
import java.util.Properties;

public class SpringWebAppInitializer extends AbstractWebAppInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {

        return new String[]{"/"};
    }

    @Override
    protected Map<String, Filter> getServletFilters() {

        Properties exceptionMapping = new Properties();
        //未登陆
        exceptionMapping.setProperty("org.apache.shiro.authz.UnauthenticatedException", "/login");
        exceptionMapping.setProperty("org.apache.shiro.authz.UnauthenticatedException", "/login");
        //未授权
        exceptionMapping.setProperty("org.apache.shiro.authz.UnauthorizedException", "/errors/403");

        exceptionMapping.setProperty("com.novunda.platform.security.LoginException", "/errors/loginError");
        exceptionMapping.setProperty("org.apache.oltu.oauth2.common.exception.OAuthProblemException", "/errors/500");
        exceptionMapping.setProperty("com.novunda.platform.common.exception.NovException", "/errors/500");

        GlobalExceptionResolverFilter resolverFilter = new GlobalExceptionResolverFilter();
        resolverFilter.setDefaultErrorView("/errors/500");
        resolverFilter.setExceptionMappings(exceptionMapping);

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        Map<String, Filter> filterMap = Maps.newLinkedHashMap();
        filterMap.put("exceptionResolverFilter", resolverFilter);
        filterMap.put("characterEncodingFilter", characterEncodingFilter);
        filterMap.put("openEntityManagerInViewFilter", new OpenEntityManagerInViewFilter());
        filterMap.put("shiroFilter", new DelegatingFilterProxy());

        return filterMap;
    }


    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        super.onStartup(servletContext);
    }

}
